package ncs.common.action;

import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import ncs.common.database.ResourceDAO;
import ncs.common.model.Resource;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class DownloadResourceAction extends ActionSupport implements ServletRequestAware,ServletContextAware{
	private static final long serialVersionUID = -1110006754311802627L;
	private HttpServletRequest request;
	private ServletContext context;
	private String filePath;
	private String fileName;
	private int	fileSize;
	@Override
	public String execute() throws Exception {
		if(request.getParameter("resource")!=null)
		{
			int id=Integer.parseInt(request.getParameter("resource"));
			Resource r=ResourceDAO.getLocalName(id, true);
			fileName=r.getName();
			fileSize=r.getSize();
			filePath=String.format("upload/%d/%s", r.getCourse_id(),fileName);
			fileName=java.net.URLEncoder.encode(fileName, "UTF-8");
		}
		return SUCCESS;
	}
	@Override
	public void setServletRequest(HttpServletRequest req) {
		this.request=req;
	}
	@Override
	public void setServletContext(ServletContext con) {
		context=con;
		
	}
	public InputStream getInputStream()throws Exception{
		return context.getResourceAsStream(filePath);
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public int getFileSize() {
		return fileSize;
	}
	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}
}
